<?php

class EICms_Form_TableRowBuilder extends EICms_Form {
	
	/**
	 * The row object.
	 *
	 * @var Zend_Db_Table_Row_Abstract
	 */
	protected $_row;
	
	/**
	 * The fieldtype mapping
	 *
	 * @var array
	 */
	protected $_typeMap = array('varchar' => 'text',
								'char' => 'text',
								'date' => 'text',
								'datetime' => 'text',
								'int' => 'text',
								'text' => 'textarea');
	
	/**
	 * The constructor
	 *
	 * @param Zend_Db_Table_Row_Abstract $row
	 * @param array $options
	 */
	public function __construct(Zend_Db_Table_Row_Abstract $row,$options = null) {
		$this->setRow($row);
		parent::__construct($options);
	}
	
	/**
	 * Init method
	 *
	 */
	public function init() {
		$tableInfo = $this->_row->getTable()->info();
		$fields = $tableInfo['metadata'];
		foreach($fields as $field => $info) {
			if($info['PRIMARY']) {
				$primary = new Zend_Form_Element_Hidden($field);
				$primary->setName($field)
						->setValue($this->_row->$field);
				continue;
			}
			
			if(empty($this->_typeMap[$info['DATA_TYPE']])) {
				throw new EICms_Form_TableRowBuilder_Exception('Datatype: ' . $info['DATA_TYPE'] . ' could not be mapped to a form element type for field: ' . $field);
			}
			else {
				$options = array('label' => ucFirst($field),
								'value' => $this->_row->$field);
				if(!$info['NULLABLE']) {
					$options['required'] = true;
				}
				$this->addElement($this->_typeMap[$info['DATA_TYPE']],$field,$options);
			}
		}
	}
	
	/**
	 * Sets the current row
	 *
	 * @param Zend_Db_Table_Row_Abstract $row
	 * @return EICms_Form_TableBuilder
	 */
	public function setRow(Zend_Db_Table_Row_Abstract $row) {
		$this->_row = $row;
		return $this;
	}
	
	/**
	 * Returns the table object.
	 *
	 * @return EICms_Table
	 */
	public function getTable() {
		return $this->_table;
	}
	
}
?>